/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VentaForm.java
 *
 * Created on 03-ago-2010, 19:54:31
 */

package stockcontrol;

import entidades.Articulo;
import entidades.Cliente;
import entidades.Vendedor;
import entidades.Venta;
import java.awt.Color;
import java.awt.EventQueue;
import java.beans.Beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.persistence.EntityManager;
import javax.persistence.RollbackException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class VentaForm extends JPanel implements Serializable {
    private Venta venta = null;

    private VendedorForm vendedorForm = null;
    private ClienteForm clienteForm = null;
    private ArticuloForm articuloForm = null;

    EntityManager entityManager;

    private List nombres = new Vector();
    List<Articulo> resultados;

    public VentaForm(EntityManager em) {
        
        entityManager = em;

        initComponents();
        
        masterTable.getSelectionModel().addListSelectionListener(
            new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    int i = masterTable.getSelectedRow();
                    if ( i >= 0 ){
                        venta = list.get(masterTable.convertRowIndexToModel(i));
                        try {
                            codigoArticuloField.setText(venta.getArticulo().getCodigo().toString());
                            codigoClienteField.setText(venta.getCliente().getCodigo().toString());
                            codigoVendedorField.setText(venta.getVendedor().getCodigo().toString());
                        } catch (Exception ex) {
                           
                        }
                    }
                }
            });

    }


    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(stockcontrol.StockControlApp.class).getContext().getResourceMap(VentaForm.class);
        query = java.beans.Beans.isDesignTime() ? null : (entityManager).createQuery(resourceMap.getString("query.query")); // NOI18N
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        articuloLabel = new javax.swing.JLabel();
        vendedorLabel = new javax.swing.JLabel();
        clienteLabel = new javax.swing.JLabel();
        fechaLabel = new javax.swing.JLabel();
        importeLabel = new javax.swing.JLabel();
        cantidadLabel = new javax.swing.JLabel();
        estadoLabel = new javax.swing.JLabel();
        articuloField = new javax.swing.JTextField();
        vendedorField = new javax.swing.JTextField();
        clienteField = new javax.swing.JTextField();
        importeField = new javax.swing.JTextField();
        cantidadField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        fechaField = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        codigoArticuloField = new javax.swing.JTextField();
        codigoVendedorField = new javax.swing.JTextField();
        codigoClienteField = new javax.swing.JTextField();
        buttonArticulos = new javax.swing.JButton();
        buttonVendedores = new javax.swing.JButton();
        buttonClientes = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        buscarField = new javax.swing.JTextField();
        estadoComboBox = new javax.swing.JComboBox();
        comisionLabel = new javax.swing.JLabel();
        comisionField = new javax.swing.JTextField();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();

        FormListener formListener = new FormListener();

        setName("Form"); // NOI18N

        articuloLabel.setText(resourceMap.getString("articuloLabel.text")); // NOI18N
        articuloLabel.setName("articuloLabel"); // NOI18N

        vendedorLabel.setText(resourceMap.getString("vendedorLabel.text")); // NOI18N
        vendedorLabel.setName("vendedorLabel"); // NOI18N

        clienteLabel.setText(resourceMap.getString("clienteLabel.text")); // NOI18N
        clienteLabel.setName("clienteLabel"); // NOI18N

        fechaLabel.setText(resourceMap.getString("fechaLabel.text")); // NOI18N
        fechaLabel.setName("fechaLabel"); // NOI18N

        importeLabel.setText(resourceMap.getString("importeLabel.text")); // NOI18N
        importeLabel.setName("importeLabel"); // NOI18N

        cantidadLabel.setText(resourceMap.getString("cantidadLabel.text")); // NOI18N
        cantidadLabel.setName("cantidadLabel"); // NOI18N

        estadoLabel.setText(resourceMap.getString("estadoLabel.text")); // NOI18N
        estadoLabel.setName("estadoLabel"); // NOI18N

        articuloField.setEditable(false);
        articuloField.setEnabled(false);
        articuloField.setName("articuloField"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.articulo.descrip}"), articuloField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        articuloField.addActionListener(formListener);

        vendedorField.setEditable(false);
        vendedorField.setEnabled(false);
        vendedorField.setName("vendedorField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.vendedor.nombre}"), vendedorField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        clienteField.setEditable(false);
        clienteField.setEnabled(false);
        clienteField.setName("clienteField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cliente.nombre}"), clienteField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        importeField.setName("importeField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.importe}"), importeField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), importeField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        importeField.addKeyListener(formListener);

        cantidadField.setName("cantidadField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cantidad}"), cantidadField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cantidadField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        cantidadField.addKeyListener(formListener);

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(formListener);

        refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
        refreshButton.setName("refreshButton"); // NOI18N
        refreshButton.addActionListener(formListener);

        newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
        newButton.setName("newButton"); // NOI18N
        newButton.addActionListener(formListener);

        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), deleteButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        deleteButton.addActionListener(formListener);

        fechaField.setName("fechaField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.fecha}"), fechaField, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), fechaField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        codigoArticuloField.setName("codigoArticuloField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.articulo.codigo}"), codigoArticuloField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), codigoArticuloField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        codigoArticuloField.addKeyListener(formListener);

        codigoVendedorField.setName("codigoVendedorField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.vendedor.codigo}"), codigoVendedorField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), codigoVendedorField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        codigoVendedorField.addKeyListener(formListener);

        codigoClienteField.setName("codigoClienteField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cliente.codigo}"), codigoClienteField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), codigoClienteField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        codigoClienteField.addKeyListener(formListener);

        buttonArticulos.setText(resourceMap.getString("buttonArticulos.text")); // NOI18N
        buttonArticulos.setName("buttonArticulos"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), buttonArticulos, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        buttonArticulos.addActionListener(formListener);

        buttonVendedores.setText(resourceMap.getString("buttonVendedores.text")); // NOI18N
        buttonVendedores.setName("buttonVendedores"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), buttonVendedores, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        buttonVendedores.addActionListener(formListener);

        buttonClientes.setText(resourceMap.getString("buttonClientes.text")); // NOI18N
        buttonClientes.setName("buttonClientes"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), buttonClientes, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        buttonClientes.addActionListener(formListener);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        buscarField.setEnabled(false);
        buscarField.setName("buscarField"); // NOI18N
        buscarField.addKeyListener(formListener);

        estadoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PAGO                ", "CONSIG." }));
        estadoComboBox.setName("estadoComboBox"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.estado}"), estadoComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), estadoComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        comisionLabel.setText(resourceMap.getString("comisionLabel.text")); // NOI18N
        comisionLabel.setName("comisionLabel"); // NOI18N

        comisionField.setName("comisionField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.comision}"), comisionField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), comisionField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        masterScrollPane.setName("masterScrollPane"); // NOI18N

        masterTable.setName("masterTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${codigo}"));
        columnBinding.setColumnName("Codigo");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${articulo}"));
        columnBinding.setColumnName("Articulo");
        columnBinding.setColumnClass(entidades.Articulo.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${vendedor}"));
        columnBinding.setColumnName("Vendedor");
        columnBinding.setColumnClass(entidades.Vendedor.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cliente}"));
        columnBinding.setColumnName("Cliente");
        columnBinding.setColumnClass(entidades.Cliente.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fecha}"));
        columnBinding.setColumnName("Fecha");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cantidad}"));
        columnBinding.setColumnName("Cantidad");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${importe}"));
        columnBinding.setColumnName("Importe");
        columnBinding.setColumnClass(Double.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${estado}"));
        columnBinding.setColumnName("Estado");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${comision}"));
        columnBinding.setColumnName("Comision");
        columnBinding.setColumnClass(Double.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 808, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(628, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(buscarField, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(refreshButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(saveButton))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(articuloLabel)
                                    .addComponent(vendedorLabel)
                                    .addComponent(clienteLabel)
                                    .addComponent(fechaLabel)
                                    .addComponent(estadoLabel))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(clienteField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(vendedorField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(articuloField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addComponent(estadoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(comisionLabel))
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(fechaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(cantidadLabel)))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(comisionField)
                                            .addComponent(cantidadField, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(18, 18, 18)
                                        .addComponent(importeLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(importeField)))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(codigoClienteField)
                                    .addComponent(codigoArticuloField)
                                    .addComponent(codigoVendedorField, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(buttonClientes, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                                    .addComponent(buttonVendedores, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                                    .addComponent(buttonArticulos, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deleteButton, newButton, refreshButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buscarField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(21, 21, 21)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(articuloLabel)
                    .addComponent(articuloField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoArticuloField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonArticulos, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vendedorLabel)
                    .addComponent(vendedorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoVendedorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonVendedores, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(clienteLabel)
                    .addComponent(clienteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigoClienteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonClientes, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaLabel)
                    .addComponent(fechaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cantidadLabel)
                    .addComponent(cantidadField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(importeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(importeLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(comisionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(comisionLabel))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(estadoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(estadoLabel)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(refreshButton)
                    .addComponent(deleteButton)
                    .addComponent(newButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == articuloField) {
                VentaForm.this.articuloFieldActionPerformed(evt);
            }
            else if (evt.getSource() == saveButton) {
                VentaForm.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                VentaForm.this.refreshButtonActionPerformed(evt);
            }
            else if (evt.getSource() == newButton) {
                VentaForm.this.newButtonActionPerformed(evt);
            }
            else if (evt.getSource() == deleteButton) {
                VentaForm.this.deleteButtonActionPerformed(evt);
            }
            else if (evt.getSource() == buttonArticulos) {
                VentaForm.this.buttonArticulosActionPerformed(evt);
            }
            else if (evt.getSource() == buttonVendedores) {
                VentaForm.this.buttonVendedoresActionPerformed(evt);
            }
            else if (evt.getSource() == buttonClientes) {
                VentaForm.this.buttonClientesActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == importeField) {
                VentaForm.this.importeFieldKeyReleased(evt);
            }
            else if (evt.getSource() == cantidadField) {
                VentaForm.this.cantidadFieldKeyReleased(evt);
            }
            else if (evt.getSource() == codigoArticuloField) {
                VentaForm.this.codigoArticuloFieldKeyReleased(evt);
            }
            else if (evt.getSource() == codigoVendedorField) {
                VentaForm.this.codigoVendedorFieldKeyReleased(evt);
            }
            else if (evt.getSource() == codigoClienteField) {
                VentaForm.this.codigoClienteFieldKeyReleased(evt);
            }
            else if (evt.getSource() == buscarField) {
                VentaForm.this.buscarFieldKeyReleased(evt);
            }
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

     public void clearAllFields(){
        clienteField.setText("");
        articuloField.setText("");
        vendedorField.setText("");
        codigoArticuloField.setText(null);
        codigoClienteField.setText(null);
        codigoVendedorField.setText(null);
        fechaField.setDate(null);
        importeField.setText(null);
        cantidadField.setText(null);
    }

    @SuppressWarnings("unchecked")
    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<entidades.Venta> toRemove = new ArrayList<entidades.Venta>(selected.length);
        for (int idx=0; idx<selected.length; idx++) {
            entidades.Venta v = list.get(masterTable.convertRowIndexToModel(selected[idx]));
            toRemove.add(v);
            entityManager.remove(v);
        }
        list.removeAll(toRemove);
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        if ( ! this.hasValidForeigns() )
            if ( masterTable.getSelectedRow() >= 0 ) {
                return;
        }       
        venta = new entidades.Venta();
        //entityManager.persist(venta);
        list.add(venta);
        int row = list.size()-1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
    }//GEN-LAST:event_newButtonActionPerformed
    
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if ( masterTable.getSelectedRow() >= 0 ) {
            if ( ! this.hasValidForeigns() )
                return;
        }
        try {
            entityManager.getTransaction().commit();
            entityManager.getTransaction().begin();
        } catch (RollbackException rex) {
            rex.printStackTrace();
            entityManager.getTransaction().begin();
            List<entidades.Venta> merged = new ArrayList<entidades.Venta>(list.size());
            for (entidades.Venta v : list) {
                merged.add(entityManager.merge(v));
            }
            list.clear();
            list.addAll(merged);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void articuloFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_articuloFieldActionPerformed
        // TODO add your handling code here:
        entityManager.clear();
        List<Articulo> l = entityManager.createNamedQuery("Articulo.findByDescrip")
                .setParameter("descrip", articuloField.getText()).getResultList();

        if ( l.size() > 1 )
            System.out.println("WARNING - more than one ARTICULO with the same name: " + articuloField.getText());
        if ( l.size() <= 0 )
            codigoArticuloField.setBackground(Color.red);
        else {
            Articulo a = l.get(0);
            venta.setArticulo(a);
            codigoArticuloField.setText( a.getCodigo().toString() );
            codigoArticuloField.setBackground(Color.WHITE);
        }

    }//GEN-LAST:event_articuloFieldActionPerformed

    private void buttonArticulosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonArticulosActionPerformed
        // TODO add your handling code here:
        articuloForm = new ArticuloForm((VentaForm)this, entityManager);
        articuloForm.showFrame();
    }//GEN-LAST:event_buttonArticulosActionPerformed

    private void buttonClientesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonClientesActionPerformed
        // TODO add your handling code here:
        clienteForm  = new ClienteForm((VentaForm)this, entityManager);
        clienteForm.showFrame();
    }//GEN-LAST:event_buttonClientesActionPerformed

    private void buttonVendedoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonVendedoresActionPerformed
        // TODO add your handling code here:
        vendedorForm = new VendedorForm((VentaForm)this, entityManager);
        vendedorForm.showFrame();
    }//GEN-LAST:event_buttonVendedoresActionPerformed

    private void buscarFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscarFieldKeyReleased
        // TODO add your handling code here:
        /*
        if ( !this.nombres.contains( buscarField.getText().trim()) ){
            buscarField.setBackground(Color.red);
            list.clear();
            list.addAll(query.getResultList());
        } else {
            buscarField.setBackground(Color.GREEN);
            resultados = entityManager.createNamedQuery("Venta.findByNombre")
                    .setParameter("descrip", buscarField.getText()).getResultList();
            list.clear();
            list.addAll(resultados);
        }

        if ( buscarField.getText().isEmpty() ){
            list.clear();
            list.addAll(query.getResultList());
            buscarField.setBackground(Color.white);
        }
         *
         */
}//GEN-LAST:event_buscarFieldKeyReleased

    private void codigoArticuloFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codigoArticuloFieldKeyReleased
        // TODO add your handling code here:
        try {
            Integer.parseInt( codigoArticuloField.getText().trim() );
            codigoArticuloField.setBackground(Color.white);
        } catch ( NumberFormatException exception ){
            codigoArticuloField.setBackground(Color.red);
        }
        if ( codigoArticuloField.getText().isEmpty() )
            codigoArticuloField.setBackground(Color.white);
    }//GEN-LAST:event_codigoArticuloFieldKeyReleased

    private void codigoVendedorFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codigoVendedorFieldKeyReleased
        // TODO add your handling code here:
        try {
            Integer.parseInt( codigoVendedorField.getText().trim() );
            codigoVendedorField.setBackground(Color.white);
        } catch ( NumberFormatException exception ){
            codigoVendedorField.setBackground(Color.red);
        }
        if ( codigoVendedorField.getText().isEmpty() )
            codigoVendedorField.setBackground(Color.white);
    }//GEN-LAST:event_codigoVendedorFieldKeyReleased

    private void codigoClienteFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codigoClienteFieldKeyReleased
        // TODO add your handling code here:
        try {
            Integer.parseInt(  codigoClienteField.getText().trim() );
             codigoClienteField.setBackground(Color.white);
        } catch ( NumberFormatException exception ){
             codigoClienteField.setBackground(Color.red);
        }
        if (  codigoClienteField.getText().isEmpty() )
             codigoClienteField.setBackground(Color.white);
    }//GEN-LAST:event_codigoClienteFieldKeyReleased

    private void cantidadFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cantidadFieldKeyReleased
        // TODO add your handling code here:
         try {
            Integer.parseInt(  cantidadField.getText().trim() );
             cantidadField.setBackground(Color.white);
        } catch ( NumberFormatException exception ){
             cantidadField.setBackground(Color.red);
        }
        if (  cantidadField.getText().isEmpty() )
             cantidadField.setBackground(Color.white);
    }//GEN-LAST:event_cantidadFieldKeyReleased

    private void importeFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_importeFieldKeyReleased
        // TODO add your handling code here:
       try {
            Float.parseFloat(   importeField.getText().trim() );
              importeField.setBackground(Color.white);
        } catch ( NumberFormatException exception ){
              importeField.setBackground(Color.red);
        }
        if (   importeField.getText().isEmpty() )
              importeField.setBackground(Color.white);
    }//GEN-LAST:event_importeFieldKeyReleased
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField articuloField;
    private javax.swing.JLabel articuloLabel;
    private javax.swing.JTextField buscarField;
    private javax.swing.JButton buttonArticulos;
    private javax.swing.JButton buttonClientes;
    private javax.swing.JButton buttonVendedores;
    private javax.swing.JTextField cantidadField;
    private javax.swing.JLabel cantidadLabel;
    private javax.swing.JTextField clienteField;
    private javax.swing.JLabel clienteLabel;
    private javax.swing.JTextField codigoArticuloField;
    private javax.swing.JTextField codigoClienteField;
    private javax.swing.JTextField codigoVendedorField;
    private javax.swing.JTextField comisionField;
    private javax.swing.JLabel comisionLabel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JComboBox estadoComboBox;
    private javax.swing.JLabel estadoLabel;
    private org.jdesktop.swingx.JXDatePicker fechaField;
    private javax.swing.JLabel fechaLabel;
    private javax.swing.JTextField importeField;
    private javax.swing.JLabel importeLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private java.util.List<entidades.Venta> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton newButton;
    private javax.persistence.Query query;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField vendedorField;
    private javax.swing.JLabel vendedorLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void setVendedor(Vendedor v){
        if ( v != null ){
            venta.setVendedor(v);
            vendedorField.setText(v.getNombre());
            codigoVendedorField.setText(v.getCodigo().toString());
        }
    }

    public void setCliente(Cliente c){
        if ( c != null ){
            venta.setCliente(c);
            clienteField.setText(c.getNombre());
            codigoClienteField.setText(c.getCodigo().toString());
        }
    }

    public void setArticulo(Articulo a){
        if ( a != null ){
            venta.setArticulo(a);
            articuloField.setText(a.getDescrip());
            codigoArticuloField.setText(a.getCodigo().toString());
        }
    }

    public boolean hasValidForeigns(){
        boolean ok = true;
        
        if ( venta == null ) return false;

        if ( venta.getArticulo() == null ){
            codigoArticuloField.setBackground(Color.red);
            ok = false;
        } else
            codigoArticuloField.setBackground(Color.white);
        if ( venta.getCliente() == null ){
            codigoClienteField.setBackground(Color.red);
            ok = false;
        } else
            codigoClienteField.setBackground(Color.white);
        if ( venta.getVendedor() == null){
            codigoVendedorField.setBackground(Color.red);
            ok = false;
        } else
            codigoVendedorField.setBackground(Color.white);
        return ok;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Venta");
                frame.setContentPane(new VentaForm(null));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public void showFrame(){
        JFrame frame = new JFrame("Venta");
        frame.setContentPane(this);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

}
